<template>
  <div class="dialog-container">
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="Plus" @click="handleAdd"
          v-hasPermi="['basic:routeRegion:add']">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate"
          v-hasPermi="['basic:routeRegion:edit']">修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete"
          v-hasPermi="['basic:routeRegion:remove']">删除</el-button>
      </el-col>
    </el-row>

    <el-table v-loading="loading" :data="routeRegionList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="名称" align="center" prop="name" />
      <el-table-column label="场区类型" align="center" prop="type">
        <template #default="scope">
          <dict-tag :options="basic_route_region_type" :value="scope.row.type" />
        </template>
      </el-table-column>
      <el-table-column label="状态" align="center" prop="status">
        <template #default="scope">
          <dict-tag :options="sys_data_status" :value="scope.row.status" />
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize"
      @pagination="getList" />

    <!-- 添加或修改线路场区对话框 -->
    <el-dialog :title="title" v-model="open" width="800px" append-to-body>
      <el-form ref="routeRegionRef" :model="form" :rules="rules" label-width="80px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="名称" prop="name">
              <el-input v-model="form.name" placeholder="请输入名称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="站点类型" prop="type">
              <el-select v-model="form.type" placeholder="请选择">
                <el-option v-for="dict in basic_route_region_type" :key="dict.value" :label="dict.label"
                  :value="dict.value"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-row :gutter="10" class="mb8">
              <el-col :span="1.5">
                <el-button type="primary" size="small" plain icon="Plus" @click="createPolygon">编辑场区</el-button>
              </el-col>
              <el-col :span="1.5">
                <el-button type="success" size="small" plain icon="Edit" @click="closePolygon">结束场区</el-button>
              </el-col>
              <el-col :span="1.5">
                <el-button type="danger" size="small" plain icon="Delete" @click="clearMap">清除</el-button>
              </el-col>
            </el-row>
          </el-col>
          <el-col :span="12">
            <el-form-item label="状态" prop="status">
              <el-select v-model="form.status">
                <el-option v-for="dict in sys_data_status" :key="dict.value" :label="dict.label"
                  :value="dict.value"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <div id="routeRegionContainer"></div>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="RouteRegion">
import { listRouteRegion, getRouteRegion, delRouteRegion, addRouteRegion, updateRouteRegion } from "@/api/basic/routeRegion";

const { proxy } = getCurrentInstance();
const { basic_route_region_type, sys_data_status } = proxy.useDict('basic_route_region_type', 'sys_data_status');
const props = defineProps({
  // 当前的值
  routeId: [Number, String]
});
const routeRegionList = ref([]);
const open = ref(false);
const buttonLoading = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    routeId: null,
  },
  rules: {
    id: [
      { required: true, message: "不能为空", trigger: "blur" }
    ],
    type: [
      { required: true, message: "场区类型不能为空", trigger: "change" }
    ],
    name: [
      { required: true, message: "名称不能为空", trigger: "blur" }
    ],
    lngLat: [
      { required: true, message: "经纬度不能为空", trigger: "blur" }
    ],
    status: [
      { required: true, message: "状态不能为空", trigger: "change" }
    ],
    deptId: [
      { required: true, message: "部门ID不能为空", trigger: "blur" }
    ],
  }
});

const { queryParams, form, rules } = toRefs(data);

/** 查询线路场区列表 */
function getList() {
  loading.value = true;
  listRouteRegion(queryParams.value).then(response => {
    routeRegionList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    type: '1',
    name: null,
    lngLat: null,
    status: '0',
    routeId: props.routeId,
  };
  proxy.resetForm("routeRegionRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加线路场区";
  nextTick(() => {
    newMap();
  })

}

/** 修改按钮操作 */
function handleUpdate(row) {
  loading.value = true
  reset();
  const _id = row.id || ids.value
  getRouteRegion(_id).then(response => {
    loading.value = false;
    form.value = response.data;
    open.value = true;
    title.value = "修改线路场区";
    let lnglats = form.value.lngLat.split(';');
    console.log(form.value.lngLat, lnglats)
    let polygonPath = []
    lnglats.forEach((item) => {
      let lnglat = item.split(',')
      polygonPath.push([lnglat[0], lnglat[1]])
    })
    console.log(polygonPath)
    Map.polygon = polygonPath
    newMap(polygonPath);
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["routeRegionRef"].validate(valid => {
    if (valid) {
      buttonLoading.value = true;
      if (form.value.lngLat == null) {
        proxy.$modal.msgError("请编辑场区");
        buttonLoading.value = false;
        return;
      }
      if (form.value.id != null) {
        updateRouteRegion(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        }).finally(() => {
          buttonLoading.value = false;
        });
      } else {
        addRouteRegion(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        }).finally(() => {
          buttonLoading.value = false;
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value;
  proxy.$modal.confirm('是否确认删除线路场区编号为"' + _ids + '"的数据项？').then(function () {
    loading.value = true;
    return delRouteRegion(_ids);
  }).then(() => {
    loading.value = true;
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {
  }).finally(() => {
    loading.value = false;
  });
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('basic/routeRegion/export', {
    ...queryParams.value
  }, `routeRegion_${new Date().getTime()}.xlsx`)
}

watch(props, (newVal, oldVal) => {
  queryParams.value.routeId = newVal.routeId
  getList()
}, { immediate: true });
import { initMap } from '@/utils/map'
import { nextTick } from "vue";

const Map = shallowReactive({
  myMap: {}, //把AMap中的方法保存在浏览器
  map: null,
  polyEditor: null,
  polygon: [],
});
async function newMap(polygonPath = []) {
  Map.myMap = await initMap();
  Map.map = new Map.myMap.Map("routeRegionContainer", {
    zoom: 11,
  });
  if (polygonPath.length > 0) {
    var polygon2 = new Map.myMap.Polygon({
      path: polygonPath
    })
    Map.map.add([polygon2]);
  }

  Map.polyEditor = new Map.myMap.PolygonEditor(Map.map);
  Map.polyEditor.on('add', function (data) {
    var polygon = data.target;
    Map.polyEditor.addAdsorbPolygons(polygon);
    polygon.on('dblclick', () => {
      Map.polyEditor.setTarget(polygon);
      Map.polyEditor.open();
    })
  })
  Map.polyEditor.on('end', function (data) {
    console.log('endDatya', data.target.getPath());
    let point = []
    let polyArr = data.target.getPath()
    polyArr.forEach((item) => {
      point.push(item.lng + ',' + item.lat)
    })
    form.value.lngLat = point.join(';');
  })


}
function createPolygon() {
  if (form.value.id) {
    clearMap();
  }
  Map.polyEditor.close();
  Map.polyEditor.setTarget();
  Map.polyEditor.open();
}
function editPolygon() {

}
function closePolygon() {
  Map.polyEditor.close();
}

function clearMap() {
  if (form.value.id) {
    form.value.lngLat = null
  }
  Map.map.clearMap();
}
</script>
<style  scoped>
#routeRegionContainer {
  padding: 0px;
  margin: 0px;
  width: 100%;
  height: 500px;
}
</style>